package ufg.inf.es.agenda.view;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import ufg.inf.es.agenda.Model.Endereco;
import ufg.inf.es.agenda.Model.Pessoa;
import ufg.inf.es.agenda.Model.Telefone;
import ufg.inf.es.agenda.presistencia.impl.GenericDAO;

/**
 * Interface gráfica da aplicação
 * 
 * @author Wilker
 */
public class FormAgenda extends javax.swing.JFrame {

    boolean estado = false;

    /**
     * Cria a Interface Gráfica
     */
    public FormAgenda() {
        initComponents();
        setLocationRelativeTo(null);
        atualizaTabela();
        legendaDeBotoes();
        this.setResizable(false);
    }

    /**
     * Define o texto contido nos botões da GUI
     */
    public final void legendaDeBotoes() {
        btDeletar.setToolTipText("Deletar");
        btEditar.setToolTipText("Editar");
        btNovo.setToolTipText("Novo");
        btSair.setToolTipText("Sair");
        btSalvar.setToolTipText("Salvar");
    }

    /**
     * Atualiza todos os campos da interface para que os mesmos fiquem sem texto
     */
    public void limpar() {
        idField1.setText("");
        nomeField1.setText("");
        dataNascimento.setText("");
        enderecoField1.setText("");
        telefone1Field1.setText("");
        telefone2Field1.setText("");
        cpf.setText("");
        setor.setText("");
        cidade.setText("");
        uf.setText("");
        cep.setText("");
        complemento.setText("");
        estado = false;
        desabilitar();

    }

    /**
     * Desabilita a edição de determinados campos
     */
    public void desabilitar() {
        nomeField1.setEnabled(false);
        dataNascimento.setEnabled(false);
        enderecoField1.setEnabled(false);
        telefone1Field1.setEnabled(false);
        telefone2Field1.setEnabled(false);
        cpf.setEnabled(false);
        complemento.setEnabled(false);
        setor.setEnabled(false);
        cidade.setEnabled(false);
        uf.setEnabled(false);
        cep.setEnabled(false);
        btNovo.setEnabled(true);
    }

    /**
     * Habilita a edição de determinados campos
     */
    public void hablilitar() {
        nomeField1.setEnabled(true);
        dataNascimento.setEnabled(true);
        enderecoField1.setEnabled(true);
        telefone1Field1.setEnabled(true);
        telefone2Field1.setEnabled(true);
        cpf.setEnabled(true);
        complemento.setEnabled(true);
        setor.setEnabled(true);
        cidade.setEnabled(true);
        uf.setEnabled(true);
        cep.setEnabled(true);
        btNovo.setEnabled(false);
    }

    /**
     * Atualiza a tabela com as informações já cadastradas.
     */
    private void atualizaTabela() {
        DefaultTableModel dtm = (DefaultTableModel) tableAgenda.getModel();
        if (dtm.getRowCount() != 0) {
            //limpa tabela
            tableAgenda.selectAll();
            int[] l = tableAgenda.getSelectedRows();
            for (int i = (l.length - 1); i >= 0; i--) {
                dtm.removeRow(l[i]);
            }
        }
        List<Pessoa> listaPessoa = GenericDAO.listarTodos(Pessoa.class);
        for (Pessoa p : listaPessoa) {
            dtm.addRow(new Object[]{p.getId(), p.getNome(), p.getCpf()});
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel2 = new javax.swing.JPanel();
        jTextFieldCampoPesquisa = new javax.swing.JTextField();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        tableAgenda = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        idField1 = new javax.swing.JTextField();
        nomeLabel1 = new javax.swing.JLabel();
        nomeField1 = new javax.swing.JTextField();
        telefone1Field1 = new javax.swing.JFormattedTextField();
        telefoneLabel1 = new javax.swing.JLabel();
        telefoneSecundarioLabel1 = new javax.swing.JLabel();
        telefone2Field1 = new javax.swing.JFormattedTextField();
        celularLabel1 = new javax.swing.JLabel();
        dataNascimento = new javax.swing.JFormattedTextField();
        enderecoField1 = new javax.swing.JTextField();
        enderecoLabel1 = new javax.swing.JLabel();
        enderecoLabel2 = new javax.swing.JLabel();
        complemento = new javax.swing.JTextField();
        setor = new javax.swing.JTextField();
        enderecoLabel3 = new javax.swing.JLabel();
        cep = new javax.swing.JTextField();
        enderecoLabel4 = new javax.swing.JLabel();
        cidade = new javax.swing.JTextField();
        enderecoLabel5 = new javax.swing.JLabel();
        uf = new javax.swing.JTextField();
        enderecoLabel6 = new javax.swing.JLabel();
        cpf = new javax.swing.JTextField();
        labelCPF = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        btDeletar = new javax.swing.JButton();
        btSalvar = new javax.swing.JButton();
        btSair = new javax.swing.JButton();
        btEditar = new javax.swing.JButton();
        btNovo = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Agenda Eletronica");

        jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jTextFieldCampoPesquisa.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jTextFieldCampoPesquisa.setText("Pesquise o nome da pessoa aqui!");
        jTextFieldCampoPesquisa.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTextFieldCampoPesquisaMouseClicked(evt);
            }
        });
        jTextFieldCampoPesquisa.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTextFieldCampoPesquisaKeyReleased(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        tableAgenda.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Id", "Nome", "CPF"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Long.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableAgenda.setColumnSelectionAllowed(true);
        tableAgenda.getTableHeader().setReorderingAllowed(false);
        tableAgenda.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tableAgendaMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tableAgenda);
        tableAgenda.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        tableAgenda.getColumnModel().getColumn(0).setMaxWidth(30);
        tableAgenda.getColumnModel().getColumn(1).setMinWidth(150);
        tableAgenda.getColumnModel().getColumn(1).setPreferredWidth(200);
        tableAgenda.getColumnModel().getColumn(1).setMaxWidth(250);
        tableAgenda.getColumnModel().getColumn(2).setMinWidth(95);
        tableAgenda.getColumnModel().getColumn(2).setPreferredWidth(95);
        tableAgenda.getColumnModel().getColumn(2).setMaxWidth(120);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 0, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 409, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 516, Short.MAX_VALUE)
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 450, Short.MAX_VALUE)
                    .addContainerGap()))
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel1.setText("Id:");

        idField1.setEnabled(false);

        nomeLabel1.setText("Nome:");

        nomeField1.setEnabled(false);

        try {
            telefone1Field1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        telefone1Field1.setEnabled(false);

        telefoneLabel1.setText("Telefone:");

        telefoneSecundarioLabel1.setText("Telefone S.:");

        try {
            telefone2Field1.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("(##)####-####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        telefone2Field1.setEnabled(false);

        celularLabel1.setText("Data Nascimento:");

        try {
            dataNascimento.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        dataNascimento.setEnabled(false);

        enderecoField1.setEnabled(false);

        enderecoLabel1.setText("Endereco:");

        enderecoLabel2.setText("Complemento:");

        complemento.setEnabled(false);

        setor.setEnabled(false);

        enderecoLabel3.setText("Setor:");

        cep.setEnabled(false);

        enderecoLabel4.setText("CEP:");

        cidade.setEnabled(false);

        enderecoLabel5.setText("Cidade:");

        uf.setEnabled(false);

        enderecoLabel6.setText("Estado:");

        cpf.setEnabled(false);

        labelCPF.setText("CPF:");

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(telefoneSecundarioLabel1)
                    .addComponent(nomeLabel1)
                    .addComponent(jLabel1)
                    .addComponent(telefoneLabel1)
                    .addComponent(celularLabel1)
                    .addComponent(enderecoLabel1)
                    .addComponent(enderecoLabel2)
                    .addComponent(enderecoLabel3)
                    .addComponent(enderecoLabel4)
                    .addComponent(enderecoLabel5)
                    .addComponent(enderecoLabel6)
                    .addComponent(labelCPF))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(cpf)
                    .addComponent(uf)
                    .addComponent(cidade)
                    .addComponent(cep)
                    .addComponent(complemento)
                    .addComponent(enderecoField1)
                    .addComponent(dataNascimento, javax.swing.GroupLayout.DEFAULT_SIZE, 242, Short.MAX_VALUE)
                    .addComponent(nomeField1)
                    .addComponent(telefone1Field1, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(telefone2Field1)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(idField1, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(setor, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(idField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(nomeField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(nomeLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cpf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(labelCPF))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(telefoneLabel1)
                    .addComponent(telefone1Field1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(telefoneSecundarioLabel1)
                    .addComponent(telefone2Field1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(celularLabel1)
                    .addComponent(dataNascimento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(enderecoField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(enderecoLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(complemento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(enderecoLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(setor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(enderecoLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cep, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(enderecoLabel4))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(enderecoLabel5)
                    .addComponent(cidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(11, 11, 11)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(uf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(enderecoLabel6))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        btDeletar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ufg/inf/es/agenda/imagens/cross_48.png"))); // NOI18N
        btDeletar.setEnabled(false);
        btDeletar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btDeletarActionPerformed(evt);
            }
        });

        btSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ufg/inf/es/agenda/imagens/add_48.png"))); // NOI18N
        btSalvar.setEnabled(false);
        btSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSalvarActionPerformed(evt);
            }
        });

        btSair.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ufg/inf/es/agenda/imagens/cancel_48.png"))); // NOI18N
        btSair.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btSairActionPerformed(evt);
            }
        });

        btEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ufg/inf/es/agenda/imagens/paper&pencil_48.png"))); // NOI18N
        btEditar.setEnabled(false);
        btEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEditarActionPerformed(evt);
            }
        });

        btNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/ufg/inf/es/agenda/imagens/paper_48.png"))); // NOI18N
        btNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btNovoActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(btNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btDeletar, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 444, Short.MAX_VALUE)
                .addComponent(btSair, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btNovo, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSalvar, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btEditar, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btDeletar, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btSair, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jTextFieldCampoPesquisa, javax.swing.GroupLayout.DEFAULT_SIZE, 405, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jTextFieldCampoPesquisa, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tableAgendaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tableAgendaMouseClicked
        int l = tableAgenda.getSelectedRow();
        Long n = (Long) tableAgenda.getValueAt(l, 0);
        List<Pessoa> pessoas = GenericDAO.busca(Pessoa.class, "id=" + n);
        Pessoa p = pessoas.get(0);
        String cidade = "", uf = "", rua = "", cmp = "", cep = "", tel1 = "", tel2 = "", setor = "";
        for (Endereco e : p.getEnderecos()) {
            uf = e.getEstado();
            cidade = e.getCidade();
            rua = e.getRua();
            cmp = e.getComplemento();
            setor = e.getSetor();
            cep = e.getCep();
        }
        List<Telefone> t = new ArrayList<Telefone>(p.getTelefones());
        tel1 = t.get(0).getNumero();
        tel2 = t.get(1).getNumero();
        if (t.size() > 0) {
            this.btEditar.setEnabled(true);
            limpar();
            this.idField1.setText(Long.toString(p.getId()));
            this.nomeField1.setText(p.getNome());
            this.telefone1Field1.setText(tel1);
            this.telefone2Field1.setText(tel2);
            this.dataNascimento.setText(p.getDataNascimento().toString());
            this.enderecoField1.setText(rua);
            this.setor.setText(setor);
            this.complemento.setText(cmp);
            this.cep.setText(cep);
            this.cpf.setText(p.getCpf());
            this.cidade.setText(cidade);
            this.uf.setText(uf);
            btDeletar.setEnabled(true);
            estado = true;
            System.out.println(estado);
        } else {
            JOptionPane.showMessageDialog(null, "Nome não encontrado.");
            btEditar.setEnabled(false);
            limpar();
        }

    }//GEN-LAST:event_tableAgendaMouseClicked

    private void btSairActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSairActionPerformed
        int rsp = JOptionPane.showConfirmDialog(rootPane, "Deseja realmente sair?");
        if (rsp == 0) {
            dispose();
        }      
}//GEN-LAST:event_btSairActionPerformed

    private void btSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btSalvarActionPerformed
        if (nomeField1.getText().equals("")) {
        } else {
            try {
                Pessoa pessoa = new Pessoa();
                pessoa.setCpf(this.cpf.getText());
                SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy");
                Date data = formatador.parse(this.dataNascimento.getText());
                pessoa.setDataNascimento(data);
                pessoa.setNome(this.nomeField1.getText());
                Telefone tel1 = new Telefone();
                tel1.setNumero(this.telefone1Field1.getText());
                tel1.setPessoa(pessoa);
                Telefone tel2 = new Telefone();
                tel2.setNumero(this.telefone2Field1.getText());
                tel2.setPessoa(pessoa);
                pessoa.setTelefones(new HashSet<Telefone>());
                pessoa.getTelefones().add(tel1);
                pessoa.getTelefones().add(tel2);

                pessoa.setEnderecos(new HashSet<Endereco>());

                Endereco endereco = new Endereco();
                endereco.setCep(this.cep.getText());
                endereco.setCidade(this.cidade.getText());
                endereco.setEstado(this.uf.getText());
                endereco.setComplemento(this.complemento.getText());
                endereco.setPessoa(pessoa);
                endereco.setRua(this.enderecoField1.getText());
                endereco.setSetor(this.setor.getText());

                pessoa.getEnderecos().add(endereco);

                if (estado) {
                    // atualizar dados
                    pessoa.setId(Long.parseLong(idField1.getText()));
                    GenericDAO.atualizar(pessoa);
                } else {
                    // insert
                    GenericDAO.salvar(pessoa);
                }
                estado = false;
                limpar();
                atualizaTabela();
                btDeletar.setEnabled(false);
            } 
            catch (ParseException ex) {
                JOptionPane.showMessageDialog(null, "Data Inválida");
            }
        }
}//GEN-LAST:event_btSalvarActionPerformed

    private void btDeletarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btDeletarActionPerformed
        System.out.println(estado);
        if (estado == true) {
            int rsp = JOptionPane.showConfirmDialog(rootPane, "Confirma a operação?");
            if (rsp == 0) {
                List<Pessoa> pessoa = GenericDAO.busca(Pessoa.class, "id=" + idField1.getText() + "");
                System.out.println(pessoa.size() + pessoa.get(0).getNome());
                GenericDAO.remover(pessoa.get(0));
                limpar();
                estado = false;
                btDeletar.setEnabled(false);
                btEditar.setEnabled(false);
                atualizaTabela();
                desabilitar();
            }
        }
}//GEN-LAST:event_btDeletarActionPerformed

    private void btEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEditarActionPerformed

        estado = true;
        hablilitar();
        btDeletar.setEnabled(false);
        btEditar.setEnabled(true);
        btNovo.setEnabled(true);
        btSalvar.setEnabled(true);

}//GEN-LAST:event_btEditarActionPerformed

    private void btNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btNovoActionPerformed
        limpar();
        hablilitar();
        estado = false;
        btDeletar.setEnabled(false);
        btEditar.setEnabled(false);
        btNovo.setEnabled(true);
        btSalvar.setEnabled(true);
}//GEN-LAST:event_btNovoActionPerformed

    private void jTextFieldCampoPesquisaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTextFieldCampoPesquisaMouseClicked
        jTextFieldCampoPesquisa.setText("");       
    }//GEN-LAST:event_jTextFieldCampoPesquisaMouseClicked

    private void jTextFieldCampoPesquisaKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTextFieldCampoPesquisaKeyReleased
        String str = jTextFieldCampoPesquisa.getText();
        Pessoa pessoa = new Pessoa();
        ArrayList<Pessoa> arrayPessoa = new ArrayList<Pessoa>(GenericDAO.busca(Pessoa.class, "nome like '%" + str + "%'"));
        Iterator it = arrayPessoa.iterator();
        DefaultTableModel dtm = (DefaultTableModel) tableAgenda.getModel();
        if (dtm.getRowCount() != 0) {
            //limpa tabela
            tableAgenda.selectAll();
            int[] l = tableAgenda.getSelectedRows();
            for (int i = (l.length - 1); i >= 0; i--) {
                dtm.removeRow(l[i]);
            }
        }

        for (Pessoa p : arrayPessoa) {
            dtm.addRow(new Object[]{p.getId(), p.getNome(), p.getCpf()});
        }
    }//GEN-LAST:event_jTextFieldCampoPesquisaKeyReleased

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FormAgenda().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btDeletar;
    private javax.swing.JButton btEditar;
    private javax.swing.JButton btNovo;
    private javax.swing.JButton btSair;
    private javax.swing.JButton btSalvar;
    private javax.swing.JLabel celularLabel1;
    private javax.swing.JTextField cep;
    private javax.swing.JTextField cidade;
    private javax.swing.JTextField complemento;
    private javax.swing.JTextField cpf;
    private javax.swing.JFormattedTextField dataNascimento;
    private javax.swing.JTextField enderecoField1;
    private javax.swing.JLabel enderecoLabel1;
    private javax.swing.JLabel enderecoLabel2;
    private javax.swing.JLabel enderecoLabel3;
    private javax.swing.JLabel enderecoLabel4;
    private javax.swing.JLabel enderecoLabel5;
    private javax.swing.JLabel enderecoLabel6;
    private javax.swing.JTextField idField1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField jTextFieldCampoPesquisa;
    private javax.swing.JLabel labelCPF;
    private javax.swing.JTextField nomeField1;
    private javax.swing.JLabel nomeLabel1;
    private javax.swing.JTextField setor;
    private javax.swing.JTable tableAgenda;
    private javax.swing.JFormattedTextField telefone1Field1;
    private javax.swing.JFormattedTextField telefone2Field1;
    private javax.swing.JLabel telefoneLabel1;
    private javax.swing.JLabel telefoneSecundarioLabel1;
    private javax.swing.JTextField uf;
    // End of variables declaration//GEN-END:variables
}
